package ar.uba.is2.ec.matem.dao.impl;

import java.util.Collection;
import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;

import ar.uba.is2.common.utils.HibernateUtil;
import ar.uba.is2.ec.matem.dao.MedicionDao;
import ar.uba.is2.ec.matem.modelo.Medicion;

public class MedicionDaoImpl implements MedicionDao {

	@SuppressWarnings("unchecked")
	public Collection<Medicion> obtenerUltimasMediciones() {

		Session session = null;
		try{
			session = HibernateUtil.getSession();
			session.beginTransaction();

			String query = "from Medicion m where m.id in (select max(m2.id) from Medicion m2 group by m2.nombreTr, m2.tipoMedicion)";

			Query q = session.createQuery(query);

			List<Medicion> resultados = q.list();

			session.flush();
			
			return resultados;
		} finally {
			if (session != null) {
				session.close();
			}
		}

	}

	public void guardar(Medicion medicion) {
		Session session = null;
		try {
		session = HibernateUtil.getSession();
		Transaction tx = session.beginTransaction();
		
		session.save(medicion);
		
		tx.commit();
		session.flush();
		} finally {
			if(session != null){
				session.close();
			}
        }
	}

}
